<template>
	<base-list-plus
		class="min-h-[300px]"
		:loading="loading"
		:isFinish="isFinish"
		:isEmpty="list.length === 0"
		@load="search">
		<up-feed-item
			class="mt-2"
			v-for="item in list"
			:key="item.id"
			:data="item"
			hideTags></up-feed-item>
	</base-list-plus>
</template>

<script lang="ts" setup>
import { computed, inject, Ref, watch } from 'vue'
import { BaseListPlus } from '@/components/base'
import { UpFeedItem } from '@/components/up'
import { useRequest } from '@/hooks'
import { getUserFeedsList } from '@/api/feed'
import { FeedType } from '@/types'
import { useAppStore, useFeedStore } from '@/store'

const userId = inject<Ref<string>>('userId')

const appStore = useAppStore()
const feedStore = useFeedStore()

const {
	run: runUnsettlement,
	loading: loadingUnsettlement,
	list: unsettlementList
} = useRequest<FeedType>(getUserFeedsList, {
	pageSize: 100,
	onSuccess: () => {
		feedStore.setList(unsettlementList.value, 'profile')
		search(true)
	}
})

const {
	run: runSettlemented,
	loading: loadingSettlemented,
	list: settlementedList,
	isFinish
} = useRequest<FeedType>(getUserFeedsList, {
	pageSize: 5
})

const loading = computed(() => loadingUnsettlement.value || loadingSettlemented.value)

const list = computed(() => {
	const liveList: FeedType[] = []
	const earlyList: FeedType[] = []
	unsettlementList.value.forEach((item) => {
		if (!item.outcome && item.selections.some(({ isLive }) => isLive)) {
			liveList.push(item)
		} else {
			earlyList.push(item)
		}
	})
	return [...liveList, ...earlyList, ...settlementedList.value]
})

const search = (refresh = false) => {
	runSettlemented(
		{
			locale: appStore.lang,
			oddsStyle: appStore.odds,
			currency: appStore.currency,
			orderBy: 'settled_at',
			status: 'settled',
			userId: userId!.value
		},
		{ refresh }
	)
}

watch(
	() => userId?.value,
	() => {
		if (userId?.value) {
			runUnsettlement(
				{
					locale: appStore.lang,
					oddsStyle: appStore.odds,
					currency: appStore.currency,
					orderBy: 'created_at',
					status: 'valid,invalid',
					userId: userId!.value
				},
				{ refresh: true }
			)
		}
	},
	{
		immediate: true
	}
)
</script>
